package nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;

/**
 * 散点/聚集（分散读取、聚集写入）
 *
 * Scatter 分散 ˈskætə(r)
 *
 *
 * Created by Zhou_Bing on 2018/9/26.
 */
public class ScatterGatherIO {

    public static void main(String[] args) throws IOException {

        String data = "this is Scattering and Gathering example.";
        gather(data);
        scatter();
    }

    public static void gather(String data) throws IOException {
        String relativePath = System.getProperty("user.dir");
        ByteBuffer buffer1 = ByteBuffer.allocate(8);
        ByteBuffer buffer2 = ByteBuffer.allocate(256);

        buffer1.asIntBuffer().put(512);
        buffer2.asCharBuffer().put(data);

        GatheringByteChannel channel = new FileOutputStream(relativePath+ File.separator+"out.txt").getChannel();

        channel.write(new ByteBuffer[] {buffer1,buffer2});
    }

    public static void scatter() throws IOException {

        String relativePath = System.getProperty("user.dir");
        ByteBuffer buffer1 = ByteBuffer.allocate(8);
        ByteBuffer buffer2 = ByteBuffer.allocate(256);

        ScatteringByteChannel channel = new FileInputStream(relativePath+ File.separator+"out.txt").getChannel();

        channel.read(new ByteBuffer[]{buffer1,buffer2});

        /**
         * 重头
         */
        buffer1.rewind();
        buffer2.rewind();

        int bufferOne = buffer1.asIntBuffer().get();
        String bufferTwo = buffer2.asCharBuffer().toString();

        System.out.println(bufferOne);
        System.out.println(bufferTwo);
    }
}
